<template>
  <div class="content">
    <h1 class="title"><i class="fas fa-calendar-check"></i> 预订管理</h1>
    <div class="booking-form">
      <div class="form-group">
        <label>选择房间：</label>
        <select v-model="currentBooking.roomNumber" :disabled="isEditing ||!isAuthenticated" class="select-field">
          <option value="">请选择房间</option>
          <option
            v-for="room in availableRooms"
            :value="room.number"
            :key="room.number"
          >
            {{ room.number }} ({{ room.type }}, ¥{{ room.price }})
          </option>
        </select>
      </div>

      <div class="form-group">
        <label>客人姓名：</label>
        <input v-model="currentBooking.guestName" placeholder="请输入客人姓名" class="input-field" :disabled="!isAuthenticated">
      </div>

      <div class="form-group">
        <label>客人电话：</label>
        <input v-model="currentBooking.guestPhone" placeholder="请输入客人电话" class="input-field" :disabled="!isAuthenticated">
      </div>

      <div class="form-group">
        <label>入住日期：</label>
        <input type="date" v-model="currentBooking.checkInDate" class="input-field" :min="today" :max="threeMonthsLater" :disabled="!isAuthenticated">
      </div>

      <div class="form-group">
        <label>退房日期：</label>
        <input type="date" v-model="currentBooking.checkOutDate" class="input-field" :min="currentBooking.checkInDate || today" :max="threeMonthsLater" :disabled="!isAuthenticated">
      </div>

      <div class="action-buttons">
        <button @click="isEditing ? updateBooking() : addBooking()" class="primary-button" :disabled="!isAuthenticated">
          {{ isEditing ? '更新预订' : '添加预订' }}
        </button>
        <button v-if="isEditing" @click="cancelEdit" class="secondary-button" :disabled="!isAuthenticated">取消</button>
      </div>
    </div>

    <div class="booking-list">
      <h2 class="sub-title">预订列表</h2>
      <table class="data-table">
        <thead>
          <tr>
            <th>房间号</th>
            <th>客人</th>
            <th>电话</th>
            <th>入住日期</th>
            <th>退房日期</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(booking, index) in bookings" :key="index">
            <td>{{ booking.roomNumber }}</td>
            <td>{{ booking.guestName }}</td>
            <td>{{ booking.guestPhone }}</td>
            <td>{{ formatDate(booking.checkInDate) }}</td>
            <td>{{ formatDate(booking.checkOutDate) }}</td>
            <td>
              <button @click="editBooking(index)" class="edit-button" :disabled="!isAuthenticated">编辑</button>
              <button @click="deleteBooking(index)" class="delete-button" :disabled="!isAuthenticated">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BookingManagement',
  data() {
    return {
      currentBooking: {
        roomNumber: '',
        guestName: '',
        guestPhone: '',
        checkInDate: '',
        checkOutDate: ''
      },
      isEditing: false,
      editingIndex: -1
    }
  },
  computed: {
    availableRooms() {
      return this.$store.getters.availableRooms
    },
    bookings() {
      return this.$store.state.bookings
    },
    guests() {
      return this.$store.state.guests
    },
    today() {
      const today = new Date()
      return today.toISOString().split('T')[0]
    },
    threeMonthsLater() {
      const today = new Date()
      today.setMonth(today.getMonth() + 3)
      return today.toISOString().split('T')[0]
    },
    isAuthenticated() {
      return localStorage.getItem('isAuthenticated') === 'true';
    }
  },
  methods: {
    addBooking() {
      if (!this.validateBooking()) return

      const existingGuest = this.guests.find(g => g.phone === this.currentBooking.guestPhone)

      if (existingGuest && existingGuest.name!== this.currentBooking.guestName) {
        if (!confirm(`客人电话已存在，姓名为 ${existingGuest.name}。要更新为 ${this.currentBooking.guestName} 吗？`)) {
          return
        }
      }

      this.$store.dispatch('addBooking', {
        ...this.currentBooking,
        checkInDate: this.currentBooking.checkInDate || this.getTodayDate(),
        checkOutDate: this.currentBooking.checkOutDate || this.getTomorrowDate()
      })

      this.resetForm()
      alert('预订成功！')
    },

    editBooking(index) {
      this.currentBooking = {...this.bookings[index]}
      this.isEditing = true
      this.editingIndex = index
    },

    updateBooking() {
      if (!this.validateBooking()) return

      const oldRoomNumber = this.bookings[this.editingIndex].roomNumber
      this.$store.dispatch('updateRoomStatus', {
        roomNumber: oldRoomNumber,
        status: 'available'
      })

      this.$store.commit('UPDATE_BOOKING', {
        index: this.editingIndex,
        booking: {...this.currentBooking}
      })

      this.$store.dispatch('updateRoomStatus', {
        roomNumber: this.currentBooking.roomNumber,
        status: 'occupied'
      })

      const existingGuest = this.guests.find(g => g.phone === this.currentBooking.guestPhone)
      if (existingGuest) {
        existingGuest.name = this.currentBooking.guestName
      } else {
        this.$store.commit('ADD_GUEST', {
          name: this.currentBooking.guestName,
          phone: this.currentBooking.guestPhone,
          idCard: ''
        })
      }

      this.resetForm()
      alert('预订更新成功！')
    },

    deleteBooking(index) {
      if (confirm('确定要删除此预订吗？')) {
        this.$store.dispatch('deleteBooking', index)
        alert('预订已删除')
      }
    },

    cancelEdit() {
      this.resetForm()
    },

    validateBooking() {
      if (!this.currentBooking.roomNumber) {
        alert('请选择房间')
        return false
      }
      if (!this.currentBooking.guestName) {
        alert('请输入客人姓名')
        return false
      }
      if (!this.currentBooking.guestPhone) {
        alert('请输入客人电话')
        return false
      }
      if (!this.currentBooking.checkInDate ||!this.currentBooking.checkOutDate) {
        alert('请选择入住和退房日期')
        return false
      }
      return true
    },

    resetForm() {
      this.currentBooking = {
        roomNumber: '',
        guestName: '',
        guestPhone: '',
        checkInDate: '',
        checkOutDate: ''
      }
      this.isEditing = false
      this.editingIndex = -1
    },

    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return date.toLocaleDateString()
    },

    getTodayDate() {
      return this.today
    },

    getTomorrowDate() {
      const tomorrow = new Date(this.today)
      tomorrow.setDate(tomorrow.getDate() + 1)
      return tomorrow.toISOString().split('T')[0]
    }
  }
}
</script>

<style scoped>
.content {
  margin-left: 240px;
  padding: 40px;
  background-color: #f4f6f9; 
}

.title {
  font-size: 32px;
  color: #333;
  margin-bottom: 20px;
}

.booking-form {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-group label {
  display: inline-block;
  width: 120px;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.input-field,
.select-field {
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 250px;
  font-size: 16px;
}

.action-buttons {
  margin-top: 20px;
}

.primary-button {
  padding: 12px 20px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
  margin-right: 10px;
}

.primary-button:hover {
  background-color: #0056b3;
}

.secondary-button {
  padding: 12px 20px;
  background-color: #f8f9fa;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.secondary-button:hover {
  background-color: #e2e6ea;
}

.sub-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.data-table th,
.data-table td {
  padding: 15px;
  border-bottom: 1px solid #ddd;
  text-align: left;
}

.data-table th {
  background-color: #f2f2f2;
  font-weight: 600;
}

.edit-button {
  padding: 8px 15px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.edit-button:hover {
  background-color: #218838;
}

.delete-button {
  padding: 8px 15px;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.delete-button:hover {
  background-color: #c82333;
}
</style>